package com.yc;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

//多线程的聊天开发
public class Test6_talkServer_runnable {
//    private static Logger log = Logger.getLogger(Test3_Server.class.getName());

    public static void main(String[] args) {
        ServerSocket ss=null;
        for (int i=10000;i<65535;i++) {
            try {
                //完成一台时间服务器，选择合适的端口工作
                ss = new ServerSocket(i);
                break;
            } catch (IOException e) {
                if (e instanceof BindException) {
                    System.out.println("端口："+i+"已经被占用");
                }
            }
        }
        //用info 级别记录， ServerSocket套接字创建成功的信息
        System.out.println(ss.getInetAddress().getHostAddress()+"启动了，监听了端口号：***"+ss.getLocalPort()+"....");
        //客户端通过键盘聊天窗口
        while(true){
            try{
                    Socket s = ss.accept();
                    System.out.println("客户端" + s.getRemoteSocketAddress() + "联接上来了");
                    TalkTask tt = new TalkTask(s);
                    Thread thread = new Thread(tt);
                    thread.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

class TalkTask implements  Runnable{
    //套接字流
    private Socket s;
    Scanner keyboard = new Scanner(System.in);
    public TalkTask(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        try (
                Socket s=this.s;//为什么要在这重新赋值一次，因为语法规定try要自动关闭的流必须在try()声明
                Scanner clientReader = new Scanner(s.getInputStream());
                PrintWriter pw = new PrintWriter(s.getOutputStream())
        ){
            do {
                String response =clientReader.nextLine();
                System.out.println("客户端"+s.getRemoteSocketAddress()+"对server说："+response);
                if ("bye".equalsIgnoreCase(response) ){
                    System.out.println("客户端"+s.getRemoteSocketAddress()+"主动断开与服务器的联接。。。");
                    break;
                }
                System.out.println("请输入服务器想对客户端说："+s.getRemoteSocketAddress()+" 说的话");
                String line =keyboard.nextLine();
                //用输出流将响应返回客户端
                pw.println(line);
                pw.flush();
                if ("bye".equalsIgnoreCase(line) ){
                    System.out.println("服务器要求和客服端主动断开联接"+s.getRemoteSocketAddress()+"的联接");
                    break;
                }
            } while (true);
            System.out.println("在服务器端正常结束与客服端"+s.getRemoteSocketAddress()+"聊天");
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("在服务器端正常结束与客服端"+s.getRemoteSocketAddress()+"聊天");
    }
}

